"""
监控中心
集成性能监控、模型监控和告警机制的统一接口
"""
import time
import asyncio
from typing import Dict, List, Optional, Any
import threading
from utils.logger import global_logger
from config.monitoring_config import PerformanceMonitorConfig, get_monitoring_config

# 导入各监控组件
from .performance_monitor import PerformanceMonitor, get_performance_monitor
from .model_monitor import ModelMonitor, get_model_monitor


class MonitoringCenter:
    """
    监控中心
    作为所有监控组件的统一入口点
    """
    
    _instance: Optional['MonitoringCenter'] = None
    _lock = threading.RLock()
    
    def __new__(cls):
        with cls._lock:
            if cls._instance is None:
                cls._instance = super(MonitoringCenter, cls).__new__(cls)
        return cls._instance
    
    def __init__(self):
        with self._lock:
            if not hasattr(self, '_initialized'):
                self._initialized = True
                
                # 加载配置
                self.config = get_monitoring_config()
                
                # 初始化各监控组件
                self.performance_monitor: Optional[PerformanceMonitor] = None
                self.model_monitor: Optional[ModelMonitor] = None
                
                # 状态管理
                self._running = False
                self._startup_time = 0.0
                
                global_logger.info("监控中心初始化完成")
    
    def start(self):
        """
        启动所有监控组件
        """
        if not self.config.enabled:
            global_logger.warning("监控系统已禁用")
            return False
            
        with self._lock:
            if self._running:
                global_logger.warning("监控系统已经在运行")
                return True
                
            try:
                # 启动性能监控
                if self.config.metrics.enabled or self.config.alerts.enabled or self.config.dashboard.enabled:
                    self.performance_monitor = get_performance_monitor()
                    self.performance_monitor.start()
                
                # 启动模型监控
                if self.config.model_monitor.enabled:
                    self.model_monitor = get_model_monitor()
                    self.model_monitor.start()
                
                # 更新状态
                self._running = True
                self._startup_time = time.time()
                
                global_logger.info("监控系统启动成功")
                return True
                
            except Exception as e:
                global_logger.error(f"启动监控系统失败: {e}")
                self._running = False
                return False
    
    def stop(self):
        """
        停止所有监控组件
        """
        if not self._running:
            return
            
        with self._lock:
            try:
                # 停止模型监控
                if self.model_monitor:
                    self.model_monitor.stop()
                
                # 停止性能监控
                if self.performance_monitor:
                    self.performance_monitor.stop()
                
                # 更新状态
                self._running = False
                
                global_logger.info("监控系统已停止")
                
            except Exception as e:
                global_logger.error(f"停止监控系统失败: {e}")
    
    def is_running(self) -> bool:
        """
        检查监控系统是否正在运行
        
        Returns:
            是否运行中
        """
        return self._running
    
    def get_system_status(self) -> Dict[str, Any]:
        """
        获取监控系统状态
        
        Returns:
            系统状态信息
        """
        uptime = 0.0
        if self._startup_time > 0:
            uptime = time.time() - self._startup_time
            
        return {
            "running": self._running,
            "uptime": uptime,
            "config_loaded": True,
            "components": {
                "performance_monitor": {
                    "enabled": self.config.metrics.enabled or self.config.alerts.enabled or self.config.dashboard.enabled,
                    "running": self.performance_monitor is not None and self.performance_monitor.is_running()
                },
                "model_monitor": {
                    "enabled": self.config.model_monitor.enabled,
                    "running": self.model_monitor is not None and self.model_monitor.is_running()
                }
            }
        }
    
    # ===== 指标收集接口 =====
    
    def record_metric(self, name: str, value: float, tags: Optional[Dict[str, str]] = None) -> None:
        """
        记录自定义指标
        
        Args:
            name: 指标名称
            value: 指标值
            tags: 标签字典
        """
        if not self._running or not self.config.metrics.enabled:
            return
            
        if self.performance_monitor:
            metrics_collector = self.performance_monitor.get_metrics_collector()
            if metrics_collector:
                metrics_collector.record_metric(name, value, tags)
    
    def record_request(self, endpoint: str, response_time: float, success: bool = True, 
                      error_type: Optional[str] = None) -> None:
        """
        记录API请求
        
        Args:
            endpoint: API端点
            response_time: 响应时间(ms)
            success: 是否成功
            error_type: 错误类型
        """
        if not self._running or not self.config.metrics.enabled:
            return
            
        # 记录通用指标
        tags = {"endpoint": endpoint}
        self.record_metric("api.response_time", response_time, tags)
        
        if success:
            self.record_metric("api.requests.success", 1.0, tags)
        else:
            self.record_metric("api.requests.error", 1.0, {**tags, "error_type": error_type or "unknown"})
            
        # 记录到性能监控器的请求统计
        if self.performance_monitor:
            metrics_collector = self.performance_monitor.get_metrics_collector()
            if metrics_collector:
                metrics_collector.increment_counter("app.requests.total")
                if success:
                    metrics_collector.increment_counter("app.requests.success")
                else:
                    metrics_collector.increment_counter("app.requests.error")
                metrics_collector.add_histogram("app.response_time", response_time)
    
    def record_model_request(self, request_id: str, model_name: str, backend: str, 
                           start_time: Optional[float] = None) -> None:
        """
        记录模型请求开始
        
        Args:
            request_id: 请求ID
            model_name: 模型名称
            backend: 后端类型
            start_time: 开始时间（默认当前时间）
        """
        if not self._running or not self.config.model_monitor.enabled:
            return
            
        if self.model_monitor:
            self.model_monitor.start_request(request_id, model_name, backend)
    
    def record_model_response(self, request_id: str, success: bool = True, 
                             error_message: Optional[str] = None, 
                             input_tokens: int = 0, output_tokens: int = 0) -> None:
        """
        记录模型响应
        
        Args:
            request_id: 请求ID
            success: 是否成功
            error_message: 错误信息
            input_tokens: 输入tokens数
            output_tokens: 输出tokens数
        """
        if not self._running or not self.config.model_monitor.enabled:
            return
            
        if self.model_monitor:
            self.model_monitor.end_request(
                request_id, 
                success=success,
                error_message=error_message,
                input_tokens=input_tokens,
                output_tokens=output_tokens
            )
    
    # ===== 告警管理接口 =====
    
    def add_alert_rule(self, name: str, metric_name: str, condition: str, threshold: float,
                      duration: int = 300, level: str = "warning", description: str = "") -> bool:
        """
        添加告警规则
        
        Args:
            name: 规则名称
            metric_name: 指标名称
            condition: 条件 (> < == != >= <=)
            threshold: 阈值
            duration: 持续时间(秒)
            level: 告警级别
            description: 描述
        
        Returns:
            是否添加成功
        """
        if not self._running or not self.config.alerts.enabled:
            return False
            
        if self.performance_monitor:
            alert_manager = self.performance_monitor.get_alert_manager()
            if alert_manager:
                return alert_manager.add_rule(
                    name=name,
                    metric_name=metric_name,
                    condition=condition,
                    threshold=threshold,
                    duration=duration,
                    level=level,
                    description=description
                )
        return False
    
    def remove_alert_rule(self, name: str) -> bool:
        """
        移除告警规则
        
        Args:
            name: 规则名称
        
        Returns:
            是否移除成功
        """
        if not self._running or not self.config.alerts.enabled:
            return False
            
        if self.performance_monitor:
            alert_manager = self.performance_monitor.get_alert_manager()
            if alert_manager:
                return alert_manager.remove_rule(name)
        return False
    
    def get_active_alerts(self, level: Optional[str] = None) -> List[Dict[str, Any]]:
        """
        获取活跃告警
        
        Args:
            level: 告警级别（可选，用于过滤）
        
        Returns:
            活跃告警列表
        """
        if not self._running or not self.config.alerts.enabled:
            return []
            
        if self.performance_monitor:
            alert_manager = self.performance_monitor.get_alert_manager()
            if alert_manager:
                return alert_manager.get_active_alerts(level)
        return []
    
    def acknowledge_alert(self, alert_id: str, user: str = "system") -> bool:
        """
        确认告警
        
        Args:
            alert_id: 告警ID
            user: 确认用户
        
        Returns:
            是否确认成功
        """
        if not self._running or not self.config.alerts.enabled:
            return False
            
        if self.performance_monitor:
            alert_manager = self.performance_monitor.get_alert_manager()
            if alert_manager:
                return alert_manager.acknowledge_alert(alert_id, user)
        return False
    
    def resolve_alert(self, alert_id: str, user: str = "system") -> bool:
        """
        解决告警
        
        Args:
            alert_id: 告警ID
            user: 解决用户
        
        Returns:
            是否解决成功
        """
        if not self._running or not self.config.alerts.enabled:
            return False
            
        if self.performance_monitor:
            alert_manager = self.performance_monitor.get_alert_manager()
            if alert_manager:
                return alert_manager.resolve_alert(alert_id, user)
        return False
    
    # ===== 数据查询接口 =====
    
    def get_metrics(self, pattern: Optional[str] = None, 
                   tags: Optional[Dict[str, str]] = None) -> Dict[str, List[Dict[str, Any]]]:
        """
        获取指标数据
        
        Args:
            pattern: 指标名称匹配模式
            tags: 标签过滤
        
        Returns:
            指标数据字典
        """
        if not self._running or not self.config.metrics.enabled:
            return {}
            
        if self.performance_monitor:
            metrics_collector = self.performance_monitor.get_metrics_collector()
            if metrics_collector:
                return metrics_collector.get_metrics(pattern, tags)
        return {}
    
    def get_model_metrics(self, model_name: Optional[str] = None,
                         backend: Optional[str] = None) -> Dict[str, Any]:
        """
        获取模型性能指标
        
        Args:
            model_name: 模型名称（可选，过滤条件）
            backend: 后端类型（可选，过滤条件）
        
        Returns:
            模型性能指标字典
        """
        if not self._running or not self.config.model_monitor.enabled:
            return {}
            
        if self.model_monitor:
            return self.model_monitor.get_model_metrics(model_name, backend)
        return {}
    
    def get_request_stats(self) -> Dict[str, Any]:
        """
        获取请求统计信息
        
        Returns:
            请求统计数据
        """
        if not self._running:
            return {}
            
        # 合并通用请求和模型请求的统计
        stats = {}
        
        # 通用请求统计
        if self.performance_monitor:
            metrics_collector = self.performance_monitor.get_metrics_collector()
            if metrics_collector:
                total_requests = metrics_collector.get_counter_value("app.requests.total") or 0
                success_requests = metrics_collector.get_counter_value("app.requests.success") or 0
                error_requests = metrics_collector.get_counter_value("app.requests.error") or 0
                avg_response_time = metrics_collector.get_histogram_value("app.response_time", "avg") or 0
                
                stats["general"] = {
                    "total_requests": total_requests,
                    "success_requests": success_requests,
                    "error_requests": error_requests,
                    "avg_response_time": avg_response_time,
                    "success_rate": (success_requests / total_requests * 100) if total_requests > 0 else 100
                }
        
        # 模型请求统计
        if self.model_monitor:
            stats["model"] = self.model_monitor.get_request_stats()
        
        return stats
    
    def get_dashboard_url(self) -> Optional[str]:
        """
        获取监控仪表板URL
        
        Returns:
            仪表板URL
        """
        if not self._running or not self.config.dashboard.enabled:
            return None
            
        if self.performance_monitor:
            dashboard = self.performance_monitor.get_dashboard()
            if dashboard and dashboard.is_running():
                return f"http://{self.config.dashboard.host}:{self.config.dashboard.port}"
        return None
    
    def reset_all_metrics(self) -> None:
        """
        重置所有监控指标
        """
        if not self._running:
            return
            
        # 重置性能监控指标
        if self.performance_monitor:
            metrics_collector = self.performance_monitor.get_metrics_collector()
            if metrics_collector:
                metrics_collector.reset()
        
        # 重置模型监控指标
        if self.model_monitor:
            self.model_monitor.reset_metrics()
            
        global_logger.info("所有监控指标已重置")


# 全局监控中心实例
_monitoring_center_instance: Optional[MonitoringCenter] = None


def get_monitoring_center() -> MonitoringCenter:
    """
    获取全局监控中心实例
    
    Returns:
        监控中心实例
    """
    global _monitoring_center_instance
    
    if _monitoring_center_instance is None:
        _monitoring_center_instance = MonitoringCenter()
    
    return _monitoring_center_instance


def start_monitoring() -> bool:
    """
    启动监控系统
    
    Returns:
        是否启动成功
    """
    center = get_monitoring_center()
    return center.start()


def stop_monitoring() -> None:
    """
    停止监控系统
    """
    center = get_monitoring_center()
    center.stop()


def is_monitoring_running() -> bool:
    """
    检查监控系统是否正在运行
    
    Returns:
        是否运行中
    """
    center = get_monitoring_center()
    return center.is_running()